/**
 * 邮件模板列表页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Switch,
  Tag,
  Popconfirm,
  message,
  Modal,
  Select,
  Tooltip,
  Dropdown,
  Menu,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  CopyOutlined,
  SearchOutlined,
  ReloadOutlined,
  FilterOutlined,
  MoreOutlined,
} from '@ant-design/icons';
import { history } from '@umijs/max';
import type { ColumnsType } from 'antd/es/table';
import {
  getEmailTemplates,
  deleteEmailTemplate,
  toggleTemplateStatus,
  cloneTemplate,
  type EmailTemplateItem,
  type TemplateCloneRequest,
  TemplateType,
  TemplateCategory,
} from '@/services/emailTemplate';

const { Search } = Input;
const { Option } = Select;

const EmailTemplateList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<EmailTemplateItem[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchText, setSearchText] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<TemplateCategory | undefined>();
  const [typeFilter, setTypeFilter] = useState<TemplateType | undefined>();
  const [activeOnly, setActiveOnly] = useState(false);
  const [cloneModalVisible, setCloneModalVisible] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<EmailTemplateItem | null>(null);
  const [cloneName, setCloneName] = useState('');

  // 获取邮件模板列表
  const fetchEmailTemplates = async () => {
    setLoading(true);
    try {
      const response = await getEmailTemplates({
        page: current,
        size: pageSize,
        search: searchText || undefined,
        category: categoryFilter,
        template_type: typeFilter,
        active_only: activeOnly,
      });
      setData(response.items);
      setTotal(response.total);
    } catch (error: any) {
      message.error(error.message || '获取邮件模板列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchEmailTemplates();
  }, [current, pageSize, searchText, categoryFilter, typeFilter, activeOnly]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
    setCurrent(1);
  };

  // 处理删除
  const handleDelete = async (id: number) => {
    try {
      await deleteEmailTemplate(id);
      message.success('删除成功');
      fetchEmailTemplates();
    } catch (error: any) {
      message.error(error.message || '删除失败');
    }
  };

  // 处理状态切换
  const handleToggleStatus = async (id: number) => {
    try {
      await toggleTemplateStatus(id);
      message.success('状态更新成功');
      fetchEmailTemplates();
    } catch (error: any) {
      message.error(error.message || '状态更新失败');
    }
  };

  // 处理克隆模板
  const handleClone = async () => {
    if (!selectedTemplate || !cloneName.trim()) {
      message.warning('请输入新模板名称');
      return;
    }

    try {
      const cloneData: TemplateCloneRequest = {
        template_id: selectedTemplate.id,
        new_name: cloneName.trim(),
      };
      
      await cloneTemplate(cloneData);
      message.success('模板克隆成功');
      setCloneModalVisible(false);
      setCloneName('');
      setSelectedTemplate(null);
      fetchEmailTemplates();
    } catch (error: any) {
      message.error(error.message || '模板克隆失败');
    }
  };

  // 打开克隆弹窗
  const openCloneModal = (template: EmailTemplateItem) => {
    setSelectedTemplate(template);
    setCloneName(`${template.name} - 副本`);
    setCloneModalVisible(true);
  };

  // 获取模板类型标签
  const getTypeTag = (type: TemplateType) => {
    const typeMap = {
      [TemplateType.HTML]: { color: 'blue', text: 'HTML' },
      [TemplateType.MARKDOWN]: { color: 'green', text: 'Markdown' },
      [TemplateType.PLAIN_TEXT]: { color: 'default', text: '纯文本' },
    };
    const config = typeMap[type] || typeMap[TemplateType.HTML];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取分类标签
  const getCategoryTag = (category: TemplateCategory) => {
    const categoryMap = {
      [TemplateCategory.MARKETING]: { color: 'red', text: '营销邮件' },
      [TemplateCategory.NOTIFICATION]: { color: 'orange', text: '通知邮件' },
      [TemplateCategory.NEWSLETTER]: { color: 'purple', text: '新闻邮件' },
      [TemplateCategory.WELCOME]: { color: 'cyan', text: '欢迎邮件' },
      [TemplateCategory.REMINDER]: { color: 'geekblue', text: '提醒邮件' },
      [TemplateCategory.CUSTOM]: { color: 'default', text: '自定义' },
    };
    const config = categoryMap[category] || categoryMap[TemplateCategory.CUSTOM];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 更多操作菜单
  const getMoreMenu = (record: EmailTemplateItem) => (
    <Menu>
      <Menu.Item
        key="preview"
        icon={<EyeOutlined />}
        onClick={() => history.push(`/templates/preview/${record.id}`)}
      >
        预览模板
      </Menu.Item>
      <Menu.Item
        key="clone"
        icon={<CopyOutlined />}
        onClick={() => openCloneModal(record)}
      >
        克隆模板
      </Menu.Item>
    </Menu>
  );

  // 表格列定义
  const columns: ColumnsType<EmailTemplateItem> = [
    {
      title: '模板名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: EmailTemplateItem) => (
        <div>
          <div style={{ fontWeight: 500 }}>{text}</div>
          {record.description && (
            <div style={{ fontSize: 12, color: '#666', marginTop: 2 }}>
              {record.description}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '邮件主题',
      dataIndex: 'subject',
      key: 'subject',
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text}</span>
        </Tooltip>
      ),
    },
    {
      title: '模板类型',
      dataIndex: 'template_type',
      key: 'template_type',
      render: (type: TemplateType) => getTypeTag(type),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: TemplateCategory) => getCategoryTag(category),
    },
    {
      title: '变量数量',
      dataIndex: 'variables',
      key: 'variables',
      render: (variables: string[]) => (
        <span>{variables ? variables.length : 0}</span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (isActive: boolean, record: EmailTemplateItem) => (
        <Switch
          checked={isActive}
          onChange={() => handleToggleStatus(record.id)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: EmailTemplateItem) => (
        <Space size="small">
          <Tooltip title="预览">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => history.push(`/templates/preview/${record.id}`)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => history.push(`/templates/edit/${record.id}`)}
            />
          </Tooltip>
          <Dropdown overlay={getMoreMenu(record)} trigger={['click']}>
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
          <Popconfirm
            title="确定要删除这个模板吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '邮件模板管理',
        breadcrumb: {},
      }}
    >
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space wrap>
            <Search
              placeholder="搜索模板名称或主题"
              allowClear
              style={{ width: 300 }}
              onSearch={handleSearch}
            />
            <Select
              placeholder="选择分类"
              allowClear
              style={{ width: 120 }}
              value={categoryFilter}
              onChange={setCategoryFilter}
            >
              <Option value={TemplateCategory.MARKETING}>营销邮件</Option>
              <Option value={TemplateCategory.NOTIFICATION}>通知邮件</Option>
              <Option value={TemplateCategory.NEWSLETTER}>新闻邮件</Option>
              <Option value={TemplateCategory.WELCOME}>欢迎邮件</Option>
              <Option value={TemplateCategory.REMINDER}>提醒邮件</Option>
              <Option value={TemplateCategory.CUSTOM}>自定义</Option>
            </Select>
            <Select
              placeholder="选择类型"
              allowClear
              style={{ width: 120 }}
              value={typeFilter}
              onChange={setTypeFilter}
            >
              <Option value={TemplateType.HTML}>HTML</Option>
              <Option value={TemplateType.MARKDOWN}>Markdown</Option>
              <Option value={TemplateType.PLAIN_TEXT}>纯文本</Option>
            </Select>
            <Switch
              checked={activeOnly}
              onChange={setActiveOnly}
              checkedChildren="仅显示启用"
              unCheckedChildren="显示全部"
            />
            <Button icon={<ReloadOutlined />} onClick={fetchEmailTemplates}>
              刷新
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => history.push('/templates/create')}
            >
              新建模板
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size || 10);
            },
          }}
        />
      </Card>

      {/* 克隆模板弹窗 */}
      <Modal
        title={`克隆模板 - ${selectedTemplate?.name}`}
        open={cloneModalVisible}
        onOk={handleClone}
        onCancel={() => {
          setCloneModalVisible(false);
          setCloneName('');
          setSelectedTemplate(null);
        }}
        okText="确定"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>
          <label>新模板名称：</label>
          <Input
            value={cloneName}
            onChange={(e) => setCloneName(e.target.value)}
            placeholder="请输入新模板名称"
            style={{ marginTop: 8 }}
          />
        </div>
      </Modal>
    </PageContainer>
  );
};

export default EmailTemplateList;
